package cn.com.css.taxInspection.util;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AnalysisXmlUtils {
	
	private static Logger logger = LoggerFactory.getLogger(AnalysisXmlUtils.class);
	
	public static Map<String, String> analysisXmlMap(String xml){

		Map<String, String> mapService = new HashMap<String, String>();
		Map<String, String> mapBody = new HashMap<String, String>();

		// String xml = "<service xmlns=\"http://www.chinatax.gov.cn/spec/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><head><tran_id>DZSWJ.ZHGLXT.XXFW.SQHD.MESSAGESEND</tran_id><channel_id>LNSW.ZGRJ.PJSMS</channel_id><tran_seq>C000BNFZC25001201706260505CC7AAA</tran_seq><tran_date>20170921</tran_date><tran_time>123454321</tran_time><rtn_code>0</rtn_code><rtn_msg><Code>000</Code> <Message></Message><Reason></Reason></rtn_msg><expand><name>sjry</name><value>12100000000</value></expand><expand><name>sjjg</name><value>12100000000</value></expand></head><body><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><taxML xsi:type=\"DZSWJXXFW00409Response\" xmlns=\"http://www.chinatax.gov.cn/dataspec/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><returnCode>0</returnCode><returnMessage>发送成功！</returnMessage></taxML>]]></body></service>";

		String bodyXml = String.valueOf(parseXml2Map(xml, mapService).get("body"));

		Map<String, String> bodyMap = parseXml2Map(bodyXml, mapBody);
		String returnCode = bodyMap.get("returnCode");
		String returnMessage = bodyMap.get("returnMessage");

		logger.info("resMap===" + bodyMap);
		logger.info("returnCode===" + returnCode);
		logger.info("returnMessage===" + returnMessage);
		
		return bodyMap;
	
	}
	
	
	/**
	 * 将xml转换为Map。 支持xml标签多层嵌套，并以"."分隔多级标签（不包括根节点）。 不支持XML标签重复时的情况
	 * 
	 * @param xml
	 * @param map
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private static Map<String, String> parseXml2Map(String xml, Map<String, String> map) {
		try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read(new StringReader(xml));
			Element root = doc.getRootElement();
			String path = "";
			if (map.containsKey(root.getName().trim())) {
				path = map.get(root.getName().trim());
				map.remove(root.getName().trim());
			}
			for (Iterator i = root.elementIterator(); i.hasNext();) {
				Element element = (Element) i.next();
				if (element.isTextOnly()) {
					if (path.length() > 0) {
						map.put(path + element.getName().trim(), element.getTextTrim());
					} else {
						map.put(element.getName().trim(), element.getTextTrim());
					}
				} else {
					map.put(element.getName().trim(), path + element.getName().trim() + ".");
					parseXml2Map(element.asXML(), map);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	
}

